import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 120000, // 延长到2分钟
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// 文件上传
export const uploadFile = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return api.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取分析结果
export const getAnalysis = () => {
  return api.get('/analysis')
}

// 获取组件分析
export const getComponents = () => {
  return api.get('/components')
}

// 获取重复日志
export const getDuplicates = () => {
  return api.get('/duplicates')
}

// 获取错误分类
export const getErrors = () => {
  return api.get('/errors')
}

// 获取时间分析
export const getTimeline = () => {
  return api.get('/timeline')
}

// 获取统计信息
export const getStats = () => {
  return api.get('/stats')
}

// 获取原始日志
export const getRawLogs = (page = 1, perPage = 100) => {
  return api.get('/logs/raw', {
    params: { page, per_page: perPage }
  })
}

// 搜索日志
export const searchLogs = (query = '', component = '', level = '', page = 1, perPage = 20) => {
  return api.get('/logs/search', {
    params: { q: query, component, level, page, per_page: perPage }
  })
}

// 获取可用的日志文件列表
export const getAvailableLogFiles = () => {
  return api.get('/logs/files')
}

// 获取日志文件内容
export const getLogFileContent = (filename: string, component?: string, level?: string) => {
  const params: Record<string, string> = {}
  if (component) {
    params.component = component
  }
  if (level) {
    params.level = level
  }
  return api.get(`/logs/file/${encodeURIComponent(filename)}`, { params })
}

// 获取规则配置
export const getRules = () => {
  return api.get('/rules')
}

// 更新规则配置
export const updateRules = (data: any) => {
  return api.post('/rules', data)
}

// 添加组件分类
export const addComponentCategory = (categoryName: string, components: string[]) => {
  return api.post('/rules/component', {
    category_name: categoryName,
    components
  })
}

// 删除组件分类
export const removeComponentCategory = (categoryName: string) => {
  return api.delete(`/rules/component/${categoryName}`)
}

// 添加错误分类
export const addErrorCategory = (categoryName: string, patterns: string[]) => {
  return api.post('/rules/error', {
    category_name: categoryName,
    patterns
  })
}

// 删除错误分类
export const removeErrorCategory = (categoryName: string) => {
  return api.delete(`/rules/error/${categoryName}`)
}

// 获取应用配置
export const getConfig = () => {
  return api.get('/config')
}

// 更新应用配置
export const updateConfig = (config: any) => {
  return api.post('/config', config)
}

// AI分析相关API
// AI分析日志
export const aiAnalyze = (errorCategory?: string) => {
  return api.post('/ai/analyze', errorCategory ? { error_category: errorCategory } : {})
}

// AI问答
export const aiAsk = (question: string, conversationId?: string, includeLogs?: boolean) => {
  return api.post('/ai/ask', { question, conversation_id: conversationId, include_logs: includeLogs })
}

// 流式AI问答
export const aiAskStream = async (question: string, onChunk: (chunk: string) => void, onEnd: () => void, onError: (error: string) => void, conversationId?: string, includeLogs?: boolean) => {
  try {
          const response = await fetch('http://localhost:8080/ai/ask', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ question, stream: true, conversation_id: conversationId, include_logs: includeLogs })
      })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }

    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        break
      }

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6))
            switch (data.type) {
              case 'start':
                // 开始流式输出
                break
              case 'chunk':
                onChunk(data.content)
                break
              case 'end':
                onEnd()
                return
              case 'error':
                onError(data.content)
                return
            }
          } catch (error) {
            // 忽略解析错误，继续处理下一行
          }
        }
      }
    }

    onEnd()
  } catch (error) {
    onError(`请求失败: ${error}`)
  }
}

// 获取对话历史
export const getConversationHistory = (conversationId?: string) => {
  const params = conversationId ? { conversation_id: conversationId } : {}
  return api.get('/ai/conversation', { params })
}

// 清空对话历史
export const clearConversationHistory = () => {
  return api.delete('/ai/conversation')
}

// 获取AI配置
export const getAIConfig = () => {
  return api.get('/ai/config')
}

// 更新AI配置
export const updateAIConfig = (config: any) => {
  return api.post('/ai/config', config)
}

// 获取错误分类列表
export const getErrorCategories = () => {
  return api.get('/ai/error-categories')
}

// AI模型管理相关API
// 获取所有AI模型
export const getAIModels = () => {
  return api.get('/ai/models')
}

// 添加新的AI模型
export const addAIModel = (key: string, config: any) => {
  return api.post('/ai/models', { key, config })
}

// 更新AI模型配置
export const updateAIModel = (modelKey: string, config: any) => {
  return api.put(`/ai/models/${modelKey}`, config)
}

// 删除AI模型
export const deleteAIModel = (modelKey: string) => {
  return api.delete(`/ai/models/${modelKey}`)
}

// 设置当前使用的AI模型
export const setCurrentAIModel = (modelKey: string) => {
  return api.post('/ai/models/current', { model_key: modelKey })
}

export async function getErrorTypeDetails(category: string, page = 1, pageSize = 20, getAll = true) {
  return api.get(`/errors/${encodeURIComponent(category)}/details`, {
    params: { page, page_size: pageSize, get_all: getAll }
  })
}

// ==================== 工作区管理 API ====================

// 获取工作区列表
export const getWorkspaces = () => {
  return api.get('/api/workspaces')
}

// 创建工作区
export const createWorkspace = (data: { name: string; description?: string; settings?: any }) => {
  return api.post('/api/workspaces', data)
}

// 获取指定工作区
export const getWorkspace = (workspaceId: string) => {
  return api.get(`/api/workspaces/${workspaceId}`)
}

// 更新工作区
export const updateWorkspace = (workspaceId: string, data: any) => {
  return api.put(`/api/workspaces/${workspaceId}`, data)
}

// 删除工作区
export const deleteWorkspace = (workspaceId: string) => {
  return api.delete(`/api/workspaces/${workspaceId}`)
}

// ==================== 分析会话管理 API ====================

// 获取分析会话列表
export const getAnalysisSessions = (workspaceId?: string, limit?: number) => {
  const params: any = {}
  if (workspaceId) params.workspace_id = workspaceId
  if (limit) params.limit = limit
  
  return api.get('/api/sessions', { params })
}

// 创建分析会话
export const createAnalysisSession = (data: { workspace_id: string; name: string; description?: string }) => {
  return api.post('/api/sessions', data)
}

// 获取指定分析会话
export const getAnalysisSession = (sessionId: string) => {
  return api.get(`/api/sessions/${sessionId}`)
}

// 更新分析会话
export const updateAnalysisSession = (sessionId: string, data: any) => {
  return api.put(`/api/sessions/${sessionId}`, data)
}

// 删除分析会话
export const deleteAnalysisSession = (sessionId: string) => {
  return api.delete(`/api/sessions/${sessionId}`)
}

// ==================== 对话历史管理 API ====================

// 获取会话对话历史
export const getSessionConversations = (sessionId: string, limit?: number) => {
  const params: any = {}
  if (limit) params.limit = limit
  
  return api.get(`/api/sessions/${sessionId}/conversations`, { params })
}

// 添加对话消息
export const addConversationMessage = (sessionId: string, data: { 
  message_type: string; 
  content: string; 
  context?: any 
}) => {
  return api.post(`/api/sessions/${sessionId}/conversations`, data)
}

// 清空会话对话历史
export const clearSessionConversations = (sessionId: string) => {
  return api.delete(`/api/sessions/${sessionId}/conversations`)
}

// 加载会话到后端内存
export const loadSessionToMemory = (sessionId: string) => {
  return api.post(`/api/sessions/${sessionId}/load`)
}

// 获取会话分析结果（不加载到内存）
export const getSessionAnalysis = (sessionId: string) => {
  return api.get(`/api/sessions/${sessionId}/analysis`)
}

export const getComponentCategories = () => {
  return api.get('/component_categories')
}

export default api 